package com.roger.uia;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiCollection;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.roger.uia.constant.WifiSecurityMode;
import com.roger.uia.entity.WifiInfo;
import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.UiDraw;
import com.roger.uia.helper.UiWatch;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.manager.Package;
import com.roger.uia.helper.util.PicUtils;
import com.roger.uia.helper.util.StrUtils;
import com.roger.uia.helper.util.ZipUtils;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import lombok.Data;

import static com.roger.uia.helper.UiBase.mDevice;

@Data
public class TestDemo {
    private static final String TAG = TestDemo.class.getSimpleName();
    private static ArrayList<cases> testCase = new ArrayList<>();

    @BeforeClass
    public static void beforeClass() { }

    @Before
    public void setUp() {
        Log.d(TAG, "-- set up --");
        UiWatch.getWatcher().runSpecialWatcher();
        Package.pac().grantAllPerms(InstrumentationRegistry.getTargetContext().getPackageName());
    }

    @After
    public void tearDown() {
        Log.d(TAG, "-- tear down --");
        UiWatch.getWatcher().removeSpecialWatcher();
    }

    @AfterClass
    public static void afterClass() { }

    @Test
    public void getUrlFileInfo() {
        try {
            URL url = new URL("https://dlied4.myapp.com/myapp/1104466820/sgame/2017_com.tencent.tmgp.sgame_h9722_1.46.1.18_74d358.apk");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setUseCaches(false);
            String fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/download.apk";
            FileUtils.deleteFile(fileName);
            if (conn.getResponseCode() == 200) {
                long timestamp = conn.getLastModified();
                int size = conn.getContentLength();
                if (size > 0) {
                    InputStream is = conn.getInputStream();
                    byte[] bytes = new byte[1024];
                    int len;
                    long total = 0;
                    FileOutputStream os = new FileOutputStream(fileName);
                    Date dataS = new Date(System.currentTimeMillis());
                    while ((len = is.read(bytes)) != -1) {
                        os.write(bytes, 0, len);
                        total+=len;
//                        Log.d(TAG,"process:"+String.format("%.2f",(float) total/size*100)+"%");
                    }
                    Date dataE = new Date(System.currentTimeMillis());
                    os.close();
                    is.close();
                    Log.d(TAG, "last modified time:" + UiBase.dateFormat.format(new Date(timestamp)));
                    float downloadTime = (float) (dataE.getTime() - dataS.getTime()) / 1000;
                    float downloadRate = (float) size / 1024 / downloadTime;
                    Log.d(TAG, "file size:" + size + " bytes");
                    Log.d(TAG, "download time:" + String.valueOf(downloadTime));
                    Log.d(TAG, "download rate:" + String.format("%.2f", downloadRate));
                }
            } else {
                Log.d(TAG, "conn http fail");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Test
    public void startAtTime() {
        while (true) {
            long curTime = new Date(System.currentTimeMillis()).getTime();
            if (curTime >= timeFormatToMs("2019/10/23 14:00:00")) {
                Log.d(TAG, String.valueOf(curTime));
                break;
            } else {
                SystemClock.sleep(1000);
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    private long timeFormatToMs(String time) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calendar.getTimeInMillis();
    }

    @Test
    public void apiTest()throws Throwable  {
        String d = UiBase.direction[0];
        UiBase.checkPoint("is up",d.equals("up"));
        UiBase.clearApp("com.roger.wifimark");
        UiBase.startAct(Settings.ACTION_LOCALE_SETTINGS);
        UiBase.clickTwoObjAtTheSameTime(210,1250,400,1250,100);
        UiCollection list = new UiCollection(new UiSelector().resourceId("com.android.settings:id/list"));
        UiObject obj1=UiBase.getObj(UiBase.objSelect[0],"Auto-rotate screen");
        UiObject obj2=UiBase.getObj(UiBase.objSelect[3],"android:id/switch_widget");
        Log.d(TAG,UiBase.getObjSameLine(list,obj1,obj2).getText());
        String product = Build.PRODUCT;
        Log.d(TAG,product);
    }

    @Test
    public void grantAllPerms(){
        try{
            Bundle para= InstrumentationRegistry.getArguments();
            String pac = para.getString("key");
            if(pac == null) return;
            Context context=InstrumentationRegistry.getTargetContext();
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(pac, PackageManager.GET_PERMISSIONS);
            String[] permissions ;
            permissions = packageInfo.requestedPermissions;
            if(permissions == null) return;
            for (String p : permissions) {
                int code = packageManager.checkPermission(p, pac);
                if (code != PackageManager.PERMISSION_GRANTED)  {
                    Log.d(TAG,p);
                    mDevice.executeShellCommand("pm grant " + pac + " " + p);
                }
            }
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    @Test
    public void runRandCase() {
        addTestCase();
        Collections.shuffle(testCase);
        for(int i=0;i<testCase.size();i++){
            testCase.get(i).run(String.valueOf(i));
            testCase.get(i).run(i,String.valueOf(i));
        }
    }

    private interface cases{
        void run(String s);
        void run(int i,String s);
    }

    private void addTestCase(){
        testCase.add(new cases() {
            @Override
            public void run(String s) {
                Log.d(TAG,"case1: "+s);
            }

            @Override
            public void run(int i,String s) { }
        });

        testCase.add(new cases() {
            @Override
            public void run(String s) { }

            @Override
            public void run(int i,String s) {
                Log.d(TAG,"case2: "+ s + i);
            }
        });
    }

    @Test
    public void picTest(){
        PicUtils.pic().takeScreenshot(UiBase.filePath+"1.png");
        PicUtils.pic().takeScreenshot(UiBase.filePath+"2.png");
        if(PicUtils.pic().isPicSameAs(UiBase.filePath+"1.png",UiBase.filePath+"2.png",0.98)){
            Log.d(TAG,"the same");
        }
        if( PicUtils.pic().isPicSameAs(UiBase.filePath+"1.png",UiBase.filePath+"2.png",0.98,0,0,200,300)){
            Log.d(TAG,"the part same");
        }
    }

    @Test
    public void zipTest(){
        ZipUtils.zip().zipFile(UiBase.filePath +"TestWifiForHW",UiBase.filePath+"update.zip");
        ZipUtils.zip().zipFile(UiBase.filePath +"1.png",UiBase.filePath+"2.zip");
        ZipUtils.zip().unZipFile(UiBase.filePath +"update.zip",UiBase.filePath);
    }

    @Test
    public void pacTest() throws Throwable {
        String pac="com.roger.wificfg";
        String isi = String.valueOf(Package.pac().isAppInstalled(pac));
        Log.d(TAG,isi);
        String la = Package.pac().getAppLabel(pac);
        Log.d(TAG,la);
        String pa = Package.pac().getAppInstallPath(pac);
        Log.d(TAG,pa);
        String[] pe = Package.pac().getAppPerms(pac);
        for (String pp :pe)  Log.d(TAG,pp);
        Package.pac().grantAllPerms(pac);
        Package.pac().getOtherAppRes("com.sina.weibo");

    }

    @Test
    public void listTest() throws UiObjectNotFoundException {
        List<String> list= UiBase.getListText("com.android.settings:id/dashboard_container","android:id/title");
        for(int i=0;i<list.size();i++){
            Log.d(TAG,list.get(i));
        }
    }

    @Test
    public void contactTest(){
//        if(ContentUtils.content().existContact())  Log.d(TAG,"exist content");
//        else Log.d(TAG,"no content");
//        if(ContentUtils.content().existContact("Test"))  Log.d(TAG,"exist Test");
//        else Log.d(TAG,"no Test");
//        if(ContentUtils.content().existContact("Test1"))  Log.d(TAG,"exist Test1");
//        else Log.d(TAG,"no Test1");
//        Log.d(TAG,ContentUtils.content().getAllContactName());
//        Log.d(TAG,ContentUtils.content().getAllContactPhoneNum());
//        ContentUtils.content().addContact("xxx3","2220");
//        ContentUtils.content().updateContactPhoneNum("xxx3","1234");
//        ContentUtils.content().delContact("xxx3");
//        Log.d(TAG,ContentUtils.content().getAllSms());
//        ContentUtils.content().updateContentTargetInfo("content://com.roger.wifimark/mark","web","5678","_id=?",new String[]{"1"});
//        Log.d(TAG,ContentUtils.content().getContentTargetInfo("content://com.roger.wifimark/user","sn"));
//        Log.d(TAG,ContentUtils.content().getContentTargetInfo("content://com.roger.wifimark/mark","_id"));
        Log.d(TAG, Build.PRODUCT);
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    @Test
    public void lombokTest() throws Throwable {
        WifiInfo wifiInfo =new WifiInfo();
        wifiInfo.setPwd("123456");
        Log.d(TAG, wifiInfo.getPwd());
        Log.d(TAG,  WifiSecurityMode.NONE.getValue());
        Log.d(TAG,  WifiSecurityMode.WAP.getValue());
        UiBase.disableApp("com.google.android.music");
        UiBase.enableApp("com.google.android.music");
    }

    @Test
    public void drawTest() throws Throwable {
        UiObject root = mDevice.findObject(new UiSelector().index(0));

        UiDraw uiDraw = new UiDraw();

        Log.d(TAG,"layout:"+  uiDraw.drawObjLayout(root,1000));
        Log.d(TAG,"layout:"+  uiDraw.drawObjLayout(UiBase.getObj("reid",StrUtils.settingDashBoard),1000));
        Log.d(TAG,"layout:"+  uiDraw.drawObjLayout(UiBase.getObj("txt","存储"),1000));

        uiDraw.txt.clear();
        uiDraw.scrollObjBeginning(root);
        Log.d(TAG,"txt:"+  uiDraw.drawObjTxt(root,1000));

        uiDraw.txt.clear();
        uiDraw.scrollObjBeginning(UiBase.getObj("reid",StrUtils.settingDashBoard));
        Log.d(TAG,"txt:"+  uiDraw.drawObjTxt(UiBase.getObj("reid",StrUtils.settingDashBoard),1000));

        uiDraw.txt.clear();
        uiDraw.scrollObjBeginning(UiBase.getObj("txt","存储"));
        Log.d(TAG,"txt:"+  uiDraw.drawObjTxt(UiBase.getObj("txt","存储"),1000));






         uiDraw.handleObjClickable2(root);

    }


}
